package com.qifenqian.turbot.module.ui.restaurant

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.GridLayoutManager
import android.text.InputType
import android.view.LayoutInflater
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.TurbotEnum
import com.qifenqian.turbot.module.adapter.restaurant.CuisineAdapter
import com.qifenqian.turbot.module.contract.RestaurantContract
import com.qifenqian.turbot.module.entity.response.restaurant.CuisineEntity
import com.qifenqian.turbot.module.entity.response.restaurant.RestaurantEntity
import com.qifenqian.turbot.module.presenter.RestaurantPresenter
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.TurbotUtil
import kotlinx.android.synthetic.main.activity_restaurant_manage.*
import kotlinx.android.synthetic.main.dialog_edit_text.view.*
import kotlinx.android.synthetic.main.layout_cuisine_chooce.view.*
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

class RestaurantManageActivity : BaseActivity<RestaurantPresenter, RestaurantContract.View>(), RestaurantContract.View {
    override fun changeAddressResult(isSuccess: Boolean, code: Int, msg: String?) {}

    override fun changeBusinessTimeResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            ly_restaurant_manage_restaurant_busyness_time.setTextRight("$mOpenTime-$mCloseTime")
        } else {
            toast(msg!!)
        }
    }

    override fun changePersonConsumeResult(isSuccess: Boolean, code: Int, msg: String?, personConsume: Int) {
        if (isSuccess) {
            if (mConsumeEditDialog != null && mConsumeEditDialog!!.isShowing) {
                mConsumeEditDialog!!.dismiss()
            }
            ly_restaurant_manage_person_consume.setTextRight((personConsume / 100).toString() + "元")
            mPresenter!!.getRestaurantInfo(true)
        }
        toast(msg!!)
    }

    override fun setAvailableChooseSeatResult(isSuccess: Boolean, msg: String?, isChecked: Boolean) {
        if (isSuccess) {
            swi_restaurant_manage_booking_online.isChecked = isChecked
        }
        toast(msg!!)
    }

    private var mRestaurantEntity: RestaurantEntity? = null
    override fun getRestaurantInfoResult(isSuccess: Boolean, code: Int, msg: String?, restaurantEntity: RestaurantEntity?) {
        if (isSuccess) {
            mRestaurantEntity = restaurantEntity
            ly_restaurant_manage_short_name.setTextRight(restaurantEntity!!.shortName)
            ly_restaurant_manage_cuisine.setTextRight(restaurantEntity.cuisine)
            ly_restaurant_manage_person_consume.setTextRight((restaurantEntity.consumePerPerson / 100).toString() + "元")
            swi_restaurant_manage_booking_online.isChecked = restaurantEntity.onlineReservation == 1
            ly_restaurant_manage_restaurant_phone.setTextRight(restaurantEntity.restaurantPhone)
            ly_restaurant_manage_restaurant_busyness_time.setTextRight(restaurantEntity.openTime + "-" + restaurantEntity.closeTime)
            ly_restaurant_manage_restaurant_address.setTextRight(restaurantEntity.province + restaurantEntity.city + restaurantEntity.area + restaurantEntity.address)
            mCurrentCuisines = try {
                restaurantEntity.cuisine.split("，") as MutableList<String>
            } catch (e: Exception) {
                mutableListOf(restaurantEntity.cuisine)
            }
        }
    }

    override fun editShortNameResult(isSuccess: Boolean, code: Int, msg: String?, shortName: String?) {
        if (isSuccess) {
            if (mShortNameEditDialog != null) {
                mShortNameEditDialog!!.dismiss()
            }
            ly_restaurant_manage_short_name.setTextRight(shortName!!)
        }
        toast(msg!!)
    }

    override fun getCuisineListResult(isSuccess: Boolean, code: Int, msg: String?, cuisineEntities: List<CuisineEntity>?) {
        if (isSuccess) {
            showCuisineDialog(cuisineEntities!!)
        } else {
            toast(msg!!)
        }
    }

    override fun chooseCuisineResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            if (mCuisineDialog != null && mCuisineDialog!!.isShowing) {
                mCuisineDialog!!.dismiss()
            }
            mPresenter!!.getRestaurantInfo(true)
        } else {
            toast(msg!!)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_restaurant_manage
    }

    override fun bindPresenter(): RestaurantPresenter? {
        return RestaurantPresenter(this, this)
    }

    companion object {
        fun startThis(context: Context) {
            val intent = Intent(context, RestaurantManageActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initial() {
        ly_restaurant_manage_short_name.setOnClickListener {
            showShortNameEditDialog()
        }
        ly_restaurant_manage_cuisine.setOnClickListener {
            // DO: 2018/12/19 获取菜系 ----->
            mPresenter!!.getCuisineList()
        }
        ly_restaurant_manage_table_info.setOnClickListener {
            // DONE: 2018/12/20 餐桌信息 ----->
            RestaurantTableActivity.startThis(this)
        }
        ly_restaurant_manage_person_consume.setOnClickListener {
            // DO: 2018/12/26 显示设置人均消费对话框 ----->
            showConsumeEditDialog()
        }
        ly_restaurant_manage_restaurant_service.setOnClickListener {
            // DONE: 2018/12/20 餐厅服务 ----->
            RestaurantServiceActivity.startThis(this)
        }
        swi_restaurant_manage_booking_online.setOnCheckedChangeListener { buttonView, isChecked ->
            if (!buttonView.isPressed) {
                return@setOnCheckedChangeListener
            }
            // DO: 2018/12/20 14:09 在线选座开关 ----->
            mPresenter!!.setAvailableChooseSeat(if (isChecked) TurbotEnum.TYPE_ONLINE_BOOKING_YES.type else TurbotEnum.TYPE_ONLINE_BOOKING_NO.type, isChecked)
        }
        ly_restaurant_manage_restaurant_introduction.setOnClickListener {
            // DO: 2018/12/20 9:34 餐厅介绍 ----->
            RestaurantIntroductionActivity.startThis(this, mRestaurantEntity!!.introduction)
        }
        ly_restaurant_manage_restaurant_phone.setOnClickListener {
            // DO: 2018/12/20 9:33 餐厅电话 ----->
            showPhoneEditDialog()
        }
        ly_restaurant_manage_restaurant_photo.setOnClickListener {
            // DONE: 2018/12/20 餐厅照片 ----->
            RestaurantPhotoActivity.startThis(this)
        }
        ly_restaurant_manage_restaurant_busyness_time.setOnClickListener {
            // DO: 2018/12/20 9:35 营业时间 ----->
            showTimePickerDialog()
        }
        ly_restaurant_manage_restaurant_address.setOnClickListener {
            // DO: 2018/12/20 14:07 餐厅地址 ----->
            RestaurantAddressActivity.startThis(this, mRestaurantEntity!!.province, mRestaurantEntity!!.city, mRestaurantEntity!!.area, mRestaurantEntity!!.address)
        }
    }

    override fun onResume() {
        super.onResume()
        Lcat.d("onResume", "onResume")
        mPresenter!!.getRestaurantInfo(true)
    }

    private var mCurrentCuisines: MutableList<String> = mutableListOf()

    private var mShortNameEditDialog: Dialog? = null
    private fun showShortNameEditDialog() {
        mShortNameEditDialog = Dialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null)
        mShortNameEditDialog!!.setContentView(view)
        mShortNameEditDialog!!.show()
        view.tv_dialog_edit_title.text = "店铺简称编辑"
        view.et_dialog_edit_content.setText(mRestaurantEntity?.shortName)
        view.btn_dialog_edit_cancel.setOnClickListener { mShortNameEditDialog!!.dismiss() }
        view.btn_dialog_edit_ok.setOnClickListener {
            // TODO: 2018/12/19 16:40 修改简称 ----->
            if (view.et_dialog_edit_content.text.toString().isEmpty()) {
                toast("店铺简称不能为空")
                return@setOnClickListener
            }
            mPresenter!!.editShortName(view.et_dialog_edit_content.text.toString().trim())
        }
    }

    private var mCuisineDialog: BottomSheetDialog? = null
    private fun showCuisineDialog(cuisineEntities: List<CuisineEntity>) {
        mCuisineDialog = BottomSheetDialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.layout_cuisine_chooce, null)
        for (cuisineEntity in cuisineEntities) {
            for (currentCuisine in mCurrentCuisines) {
                if (cuisineEntity.cuisineName == currentCuisine) {
                    cuisineEntity.isChecked = true
                }
            }
        }
        view.rv_cuisine_choose.layoutManager = GridLayoutManager(this, 3)
        view.rv_cuisine_choose.adapter = CuisineAdapter(cuisineEntities)
        view.btn_cuisine_choose_cancel.setOnClickListener {
            mCuisineDialog!!.dismiss()
        }
        view.btn_cuisine_choose_ok.setOnClickListener {
            val chooseCuisines = mutableListOf<String>()
            var chooseCuisineString = ""
            for (cuisineEntity in cuisineEntities) {
                if (cuisineEntity.isChecked) {
                    chooseCuisines.add(cuisineEntity.cuisineName)
                } else {
                    chooseCuisines.remove(cuisineEntity.cuisineName)
                }
            }
            when {
                chooseCuisines.size < 1  -> {
                    toast("至少选择一种菜系")
                    return@setOnClickListener
                }
                chooseCuisines.size > 2  -> {
                    toast("最多只能选择两种菜系")
                    return@setOnClickListener
                }
                chooseCuisines.size == 1 -> chooseCuisineString = chooseCuisines[0]
                chooseCuisines.size == 2 -> chooseCuisineString = chooseCuisines[0] + "，" + chooseCuisines[1]
            }
            // TODO: 2018/12/25 20:06 编辑菜系接口 ----->
            mPresenter!!.chooseCuisine(chooseCuisineString)
        }
        mCuisineDialog!!.setContentView(view)
        mCuisineDialog!!.show()
    }

    private var mConsumeEditDialog: Dialog? = null

    private fun showConsumeEditDialog() {
        mConsumeEditDialog = Dialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null)
        mConsumeEditDialog!!.setContentView(view)
        mConsumeEditDialog!!.show()
        view.tv_dialog_edit_title.text = "设置人均消费(元)"
        view.et_dialog_edit_content.setText((mRestaurantEntity?.consumePerPerson!! / 100).toString())
        view.et_dialog_edit_content.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        view.btn_dialog_edit_cancel.setOnClickListener { mConsumeEditDialog!!.dismiss() }
        view.btn_dialog_edit_ok.setOnClickListener {
            // TODO: 2018/12/19 16:40 修改简称 ----->
            if (view.et_dialog_edit_content.text.toString().isEmpty()) {
                toast("请设置人均消费金额")
                return@setOnClickListener
            }
            mPresenter!!.changePersonConsume((view.et_dialog_edit_content.text.toString().trim().toDouble() * 100).toInt())
        }
    }

    private var mPhoneEditDialog: Dialog? = null

    private fun showPhoneEditDialog() {
        mPhoneEditDialog = Dialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null)
        mPhoneEditDialog!!.setContentView(view)
        mPhoneEditDialog!!.show()
        view.tv_dialog_edit_title.text = "设置联系电话"
        view.et_dialog_edit_content.setText(mRestaurantEntity?.restaurantPhone)
        view.btn_dialog_edit_cancel.setOnClickListener { mPhoneEditDialog!!.dismiss() }
        view.btn_dialog_edit_ok.setOnClickListener {
            // DO: 2018/12/19 16:40 修改简称 ----->
            if (view.et_dialog_edit_content.text.toString().isEmpty()) {
                toast("请输入联系电话")
                return@setOnClickListener
            }
            mPresenter!!.changeRestaurantPhone(view.et_dialog_edit_content.text.toString().trim())
        }
    }

    private var mOpenTime: String = "08:00"
    private var mCloseTime: String = "22:00"

    private fun showTimePickerDialog() {
        TimePickerBuilder(this, OnTimeSelectListener { date1, v ->
            mOpenTime = getTime(date1)
            // DONE: 2018/12/20 选择了开始时间之后,才弹出选择结束时间 ----->
            TimePickerBuilder(this, OnTimeSelectListener { date2, v ->
                mCloseTime = getTime(date2)
                mPresenter!!.changeBusinessTime(mOpenTime, mCloseTime)
            }).setTitleText("请选择结束时间")
                    .setTitleSize(16)
                    .setDate(TurbotUtil.getCalendar(mRestaurantEntity!!.closeTime, "HH:mm")!!)
                    .setTitleColor(resources.getColor(R.color.black_333333))
                    .setType(booleanArrayOf(false, false, false, true, true, false))
                    .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                    .build()
                    .show()
        }).setTitleText("请选择开始时间")
                .setTitleSize(16)
                .setDate(TurbotUtil.getCalendar(mRestaurantEntity!!.openTime, "HH:mm")!!)
                .setTitleColor(resources.getColor(R.color.black_333333))
                .setType(booleanArrayOf(false, false, false, true, true, false))
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build()
                .show()
    }

    private fun getTime(date: Date): String {
        val format = SimpleDateFormat("HH:mm")
        return format.format(date)
    }

    override fun changeRestaurantPhoneResult(isSuccess: Boolean, code: Int, msg: String?, phone: String) {
        if (isSuccess) {
            if (mPhoneEditDialog != null && mPhoneEditDialog!!.isShowing) {
                mPhoneEditDialog!!.dismiss()
            }
            ly_restaurant_manage_restaurant_phone.setTextRight(phone)
            mPresenter!!.getRestaurantInfo(true)
        }
        toast(msg!!)
    }
}
